<?php
/** 
 * EGP Framework
 *
 * LICENSE
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 * @copyright  Copyright (c) 2008 (http://www.tblog.com.cn)
 * @license    http://www.gnu.org/licenses/gpl.html     GPL 3
 */

!defined('EGP_LIB_DIR') && die('Access Deny!');

/**
 * Controller 动作分发器
 *
 * @package    classes
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 * @copyright  Copyright (c) 2008 (http://www.tblog.com.cn)
 * @license    http://www.gnu.org/licenses/gpl.html     GPL 3
 */
abstract class EGP_Controller_Action
{

    /**
     * EGP_View
     *
     * @var EGP_View
     */
    public $view = null;

    /**
     * EGP_Http_Request
     *
     * @var EGP_Http_Request
     */
    public $request = null;

    /**
     * 构造方法
     *
     */
    public function __construct()
    {
        $this->request = EGP_Http_Request::getInstance();
        $this->setView(new EGP_View($this))->initView();
    }

    /**
     * 初始化方法
     *
     */
    public function init()
    {
    }

    /**
     * 获取 EGP_Controller_Front
     *
     * @return EGP_Controller_Front
     */
    public function getFrontController()
    {
        return EGP_Controller_Front::getInstance();
    }

    /**
     * 设置 VIEW
     *
     * @param  mixed  $view
     * @return EGP_View
     */
    public function setView(EGP_View $view)
    {
        $this->view = $view;
        return $this;
    }

    /**
     * 初始化 VIEW
     *
     * @return EGP_View|null
     */
    public function initView()
    {
        if ($this->view instanceof EGP_View) {
            $this->view->setScriptPath($this->getFrontController()
                                            ->getModule($this->getParam('module'))
                                            ->getViewDirectory());
        }
        return $this->view;
    }

    /**
     * 获取 VIEW
     *
     * @return EGP_View|null
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * 设置 EGP_Http_Request 参数
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return EGP_Http_Request
     */
    public function setParam($key, $value = null)
    {
        return $this->request->setParam($key, $value);
    }

    /**
     * 获取 EGP_Http_Request 参数
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    public function getParam($key, $default = null)
    {
        return $this->request->getParam($key, $default);
    }

    /**
     * 设置 EGP_Http_Request 参数
     *
     * @param  array  $params
     * @return EGP_Http_Request
     */
    public function setParams(array $params)
    {
        return $this->request->setParams($params);
    }

    /**
     * 获取 EGP_Http_Request 参数
     *
     * @return array
     */
    public function getParams()
    {
        return $this->request->getParams();
    }

    /**
     * 重定向页面
     *
     * @param  string  $url
     */
    public function redirect($url = '/')
    {
        EGP_Http::redirect($url);
    }

    /**
     * 根据参数生成URL地址
     *
     * @param  array    $params      需要传递的参数
     * @param  boolean  $clearOther  是否清理其他的 QUERY 参数
     * @return string
     */
    public function url(array $params = array(), $clearOther = false)
    {
        $request = $this->request;

        $scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';

        $module = isset($params['module']) ? $params['module'] : $request->getParam('module');
        $controller = isset($params['controller']) ? $params['controller'] : $request->getParam('controller');
        $action = isset($params['action']) ? $params['action'] : $request->getParam('action');

        $host = $request->getHttpHost();
        $path = "/$module/$controller/$action";

        $frontController = $this->getFrontController();
        if ($frontController->getModule($module) !== false) {
            $hosts = $frontController->getModule($module)->getHostList();
            if (isset($hosts[0])) {
                if ($module == $request->getParam('module')) {
                    $host == $hosts[0] && $path = "/$controller/$action";
                } else {
                    $host = $hosts[0];
                    $path = "/$controller/$action";
                }
            }
        }
        unset($params['module'], $params['controller'], $params['action']);

        if (false === $clearOther) {
            $query = $request->getQuery();
            !is_array($query) && $query = array();
            $params = array_merge($query, $params);
        }

        foreach ($params as $key => $value) {
            if ($value != null && $value != '')
                $path .= "/$key/$value";
        }

        $url = "$scheme://$host" . $request->getBaseUrl() . $path;
        return preg_replace('/(\/index\/?){1,3}$/', '/', $url);
    }

    /**
     * 前往指定的 action-controller-module
     *
     * @param  string  $actionName
     * @param  string  $controllerName
     * @param  string  $moduleName
     * @return EGP_Controller_Action
     */
    public function forward($action, $controller = null, $module = null)
    {
        null == $controller && $controller = $this->getParam('controller');
        null == $module && $module = $this->getParam('module');
        $this->getFrontController()->forward($action, $controller, $module);
        return $this;
    }

    /**
     * 控制器发送结束前进行预处理操作
     *
     */
    public function preDispatch()
    {}

    /**
     * 发送控制器结束操作
     *
     */
    public function dispatch()
    {
        $this->preDispatch();
        if ($this->view instanceof EGP_View) {
            $filename = $this->getParam('controller') . DIR_SEP . $this->getParam('action');
            $this->view->render($filename);
        }
    }

    /**
     * Action 不存在时通过魔术方法触发该方法调用的内容
     *
     * @param  mixed  $method
     * @param  mixed  $args
     */
    public function __call($method, $args)
    {
        $this->noRouter($method, $args);
    }

    /**
     * 未找到 Action 时的处理方法
     *
     * @param unknown_type $method
     * @param unknown_type $args
     */
    public function noRouter($method, $args)
    {
        EGP_Http::_404(sprintf(EGP_Controller_Front::NOT_FOUND_ACTION,
                               $this->getParam('module'),
                               $this->getParam('controller'),
                               $method));
        die();
    }

}